package com.itheima.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CommonConfig {
	@Bean
	public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate) {
		return new RepublishMessageRecoverer(
				rabbitTemplate, "error.direct", "error"
		);
	}

	//声明一个队列,设置超时时间，用于倒计时
	@Bean
	public Queue ttlQueue() {
		return QueueBuilder.durable("ttl.queue") // 指定队列名称，并持久化
					   .ttl(10000) // 设置队列的超时时间，10秒
					   .deadLetterExchange("dl.ttl.exchange") // 指定死信交换机
					   .deadLetterRoutingKey("dl")
					   .build();
	}
	
	//声明用于倒计时队列的交换机
	@Bean
	public DirectExchange ttlExchange() {
		return new DirectExchange("ttl.direct");
	}
	
	//绑定用于倒计时队列到对应的交换机
	@Bean
	public Binding ttlBinding(Queue ttlQueue, DirectExchange ttlExchange) {
		return BindingBuilder.bind(ttlQueue).to(ttlExchange).with("ttl");
	}
}
